<?php

declare (strict_types = 1);

namespace app\tpwork\helps;

use Error;
use own\helps\RespCode;
use own\helps\OwnDecrypt;
use own\helps\OwnFunc;
use own\helps\OwnLogger;
use think\Exception;

/**
 * 异步处理
 */
class Async
{
    /**
     * 异步投递
     * @param array|string|integer $data 数据参数
     * @param string $class 类名
     * @param string $method 方法名
     */
    public static function send($data, string $class, string $method): void
    {
        $param = [
            'data' => $data, 'class' => $class, 'method' => $method,
            'sign' => OwnDecrypt::encrypt('tp-async')
        ];
        $res = OwnFunc::curlPost('http://127.0.0.1:9523', $param);
        if($res['code'] != RespCode::SUCCESS) {
            OwnLogger::warning('异步任务投递失败');
        }
    }
    /**
     * 执行异步业务
     * @param string $class 类名
     * @param string $method 方法名
     * @param array|string|integer $data 数据参数
     */
    public static function handle(string $class, string $method, $data): void
    {
        try {
            //执行异步业务逻辑
            call_user_func_array([make($class), $method], [$data]);
        } catch (Exception $e) {
            if(is_array($data)) {
                $data = json_encode($data);
            }
            OwnLogger::other('debug', '1', $data, $e->getMessage(), "任务地址：{$class}::{$method}");
        } catch (Error $e) {
            if(is_array($data)) {
                $data = json_encode($data);
            }
            OwnLogger::other('debug', '1', $data, $e->getMessage(), "任务地址：{$class}::{$method}");
        }
    }
}
